package com.ayh.campusfun.controller.api.v1.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ayh.campusfun.entity.Message;
import com.ayh.campusfun.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ayh
 * @create 2021/3/26 0026 17:28
 * MyWebsocketServer
 */


@ServerEndpoint("/chat/{uid}")
@Component
@Slf4j
public class MyWebSocket {

    private static  MessageService messageService;

    @Autowired
    public void setMessageService(MessageService messageService){
        MyWebSocket.messageService = messageService;
    }

    //保存所有在线socket连接
    public static final Map<String,MyWebSocket> webSocketMap = new LinkedHashMap<>();

    //记录当前在线数目
    private static int count=0;

    //当前连接（每个websocket连入都会创建一个MyWebSocket实例
    private Session session;

    //处理连接建立
    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid){
        this.session = session;
        webSocketMap.put(uid,this);
        addCount();
        log.error("新的连接加入：{}",session.getId());
    }

    //接受消息
    @OnMessage
    public void onMessage(String message,Session session)  {
        log.error("收到客户端{}消息：{}",session.getId(),message);
        try {
            Message msg = JSON.parseObject(message, new TypeReference<Message>() {
            });
            if (msg.getContentType() == 5){
                messageService.updateMessageStatus(msg.getUid(), msg.getToFriendId());
                return;
            }
            messageService.insert(msg);
            Message byId = messageService.findById(msg.getId());
            msg.setSendTime(byId.getSendTime());
            this.sendMessage(JSON.toJSONString(msg));
            webSocketMap.get(msg.getToFriendId()).sendMessage(JSON.toJSONString(msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //处理错误
    @OnError
    public void onError(Throwable error,Session session){
        log.info("发生错误{},{}",session.getId(),error.getMessage());
    }

    //处理连接关闭
    @OnClose
    public void onClose(){
        webSocketMap.remove(this.session.getId());
        reduceCount();
        log.info("连接关闭:{}",this.session.getId());
    }

    //群发消息

    //发送消息
    public void sendMessage(String message) throws IOException {
        //webSocketMap.get("12345676").session.getBasicRemote().sendText(message);
        this.session.getBasicRemote().sendText(message);
    }

    //广播消息
    public static void broadcast(){
        MyWebSocket.webSocketMap.forEach((k,v)->{
            try{
                v.sendMessage("这是一条测试广播");
            }catch (Exception e){
            }
        });
    }

    //获取在线连接数目
    public static int getCount(){
        return count;
    }

    //操作count，使用synchronized确保线程安全
    public static synchronized void addCount(){
        MyWebSocket.count++;
    }

    public static synchronized void reduceCount(){
        MyWebSocket.count--;
    }

}
